<?php @session_start();?>
<?php
require_once('./safe.php');
require_once('../admin/config.php');
$conn = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd);
mysql_select_db($cfg_dbname,$conn);
$sql="select * from ph_user where user_name='".$_SESSION["username"]."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sqltdk="select * from ph_tdk where 1=1";
$resulttdk=mysql_query($sqltdk);
$rowtdk=mysql_fetch_array($resulttdk);


$orders=$_POST["orders"];
$app_id=$_POST["app_id"];

if (!empty($app_id)) {
    $Balance=$row["balance"];
    for($i=0;$i<count($orders);$i++){
        if($orders[$i]["price"]<=$Balance){
            $orderno=date("His").rand(100,999);
            $sqlc = "INSERT INTO ph_order(App,Country,Keyword,Installs,Split,Ratings,rating_stars,ipad_order,language,Price,Status,Order_date,userid,orderno,Reviews,Reviews_stars)VALUES('".$orders[$i]["app_id"]."','".$orders[$i]["country_id"]."','".$orders[$i]["keyword_name"]."','".$orders[$i]["installs"]."','".$orders[$i]["split"]."','".$orders[$i]["ratings"]."','".$orders[$i]["rating_stars"]."','".$orders[$i]["ipad_order"]."','".$orders[$i]["language"]."','".$orders[$i]["price"]."','Pending','".date('Y-m-d H:i:s',time())."','".$_SESSION["userid"]."','".$orderno."','".$orders[$i]["reviews"]."','".$orders[$i]["review_stars"]."')";
            mysql_query($sqlc,$conn);
            for($t=0;$t<count($orders[$i]["custom_reviews"]);$t++){
                $sqlt = "INSERT INTO ph_reviews(title,content,orderno)VALUES('".$orders[$i]["custom_reviews"][$t]["title"]."','".$orders[$i]["custom_reviews"][$t]["content"]."','".$orderno."')";
            mysql_query($sqlt,$conn);

            }

            $Balance=$Balance-$orders[$i]["price"];
            $sqle = "INSERT INTO ph_transactions(Transaction_ID,Amount,Payment_Amount,payType,cdate,userid)VALUES('".$orderno."','".$Balance."','-".$orders[$i]["price"]."','Balance payment','".date('Y-m-d H:i:s',time())."','".$_SESSION["userid"]."')";
            mysql_query($sqle,$conn);
$sqld = "update ph_user set balance=balance-".$orders[$i]["price"]." where id='".$_SESSION["userid"]."'";
mysql_query($sqld,$conn);

        }else{
            header('Content-type:text/json');
            echo '{"status":true,"success":["Insufficient money, please add some to your account, or make an smaller order"]}';
            exit;
        }

    }
    header('Content-type:text/json');
    echo '{"status":true,"success":["Successfully created all your orders"]}';
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

                    <link rel="apple-touch-icon" sizes="180x180" href="/images/iosinstalls/favicon/apple-touch-icon.png">

            <meta name="theme-color" content="#ffffff">

        <title><?php echo $rowtdk["sitename"];?> - Dashboard</title>

        <link href="../css/customer-iosinstalls.css?id=a9a9c5930bcdb195e9ee" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="<?php if(!empty($rowtdk["fontlink"])){echo '//fonts.googleapis.com/css?family='.$rowtdk["fontlink"];}else{echo "//fonts.googleapis.com/css?family=Roboto:300,400,500";}?>">
        <style type="text/css">
            body{font-family: '<?php echo $rowtdk["fontlink"];?>';}
        </style>
        <script type="module" src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>
        <script nomodule src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine-ie11.min.js" defer></script>

    </head>

    <body class="app header-fixed sidebar-fixed aside-menu-fixed aside-menu-hidden">
    <?php include("head.php");?> 
    <?php include("left.php");?>

            <!-- Main content -->
            <main class="main">
                    <div class="container-fluid padding-top" x-data="main()" x-init="init()">
        
        <div class="row">
            <div class="col-xl-10 col-12">
                <div class="card">
                    <div class="card-header bg-primary">
                        <i class="fa fa-plus"></i> <b>New Order</b>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            All ratings includes one install. All reviews include one rating and one install.
                        </div>
                        <div class="alert alert-danger hidden" x-bind:class="{ 'hidden': errorText.length === 0 }">
                            <template x-for="message in errorText">
                                <p x-text="message"></p>
                            </template>
                        </div>
                        <div class="alert alert-success hidden" x-text="successText ? successText : ''" x-bind:class="{ 'hidden': successText === null }"></div>
                        <div class="alert alert-warning hidden" x-bind:class="{ 'hidden': lowBalance !== true }">You do not have enough money on your account to add this order</div>

                        <form id="new-order">
                            <div class="row">
                                <div class="col-12">
                                    <div class="form-group">
                                        <label>Country</label>
                                        <select id="country" name="country" class="selectpicker" autocomplete="off" data-width="100%" data-live-search="true" data-size="7" x-model="country" x-bind:disabled="appLocked">
                                            <option value="">Select country</option>
                                                                                            <option value="235" selected=&quot;selected&quot;>United States</option>
                                                                                            <option value="4" >Algeria</option>
                                                                                            <option value="8" >Anguilla</option>
                                                                                            <option value="11" >Argentina</option>
                                                                                            <option value="12" >Armenia</option>
                                                                                            <option value="14" >Australia</option>
                                                                                            <option value="15" >Austria</option>
                                                                                            <option value="16" >Azerbaijan</option>
                                                                                            <option value="18" >Bahrain</option>
                                                                                            <option value="20" >Barbados</option>
                                                                                            <option value="21" >Belarus</option>
                                                                                            <option value="22" >Belgium</option>
                                                                                            <option value="23" >Belize</option>
                                                                                            <option value="25" >Bermuda</option>
                                                                                            <option value="27" >Bolivia</option>
                                                                                            <option value="29" >Botswana</option>
                                                                                            <option value="31" >Brazil</option>
                                                                                            <option value="33" >British Virgin Islands</option>
                                                                                            <option value="34" >Brunei Darussalam</option>
                                                                                            <option value="35" >Bulgaria</option>
                                                                                            <option value="40" >Canada</option>
                                                                                            <option value="42" >Cayman Islands</option>
                                                                                            <option value="45" >Chile</option>
                                                                                            <option value="46" >China</option>
                                                                                            <option value="49" >Colombia</option>
                                                                                            <option value="53" >Costa Rica</option>
                                                                                            <option value="54" >Croatia</option>
                                                                                            <option value="57" >Cyprus</option>
                                                                                            <option value="58" >Czech Republic</option>
                                                                                            <option value="60" >Denmark</option>
                                                                                            <option value="62" >Dominica</option>
                                                                                            <option value="65" >Ecuador</option>
                                                                                            <option value="66" >Egypt</option>
                                                                                            <option value="67" >El Salvador</option>
                                                                                            <option value="70" >Estonia</option>
                                                                                            <option value="75" >Finland</option>
                                                                                            <option value="76" >France</option>
                                                                                            <option value="83" >Germany</option>
                                                                                            <option value="84" >Ghana</option>
                                                                                            <option value="86" >Greece</option>
                                                                                            <option value="88" >Grenada</option>
                                                                                            <option value="91" >Guatemala</option>
                                                                                            <option value="95" >Guyana</option>
                                                                                            <option value="98" >Honduras</option>
                                                                                            <option value="99" >Hong Kong</option>
                                                                                            <option value="101" >Iceland</option>
                                                                                            <option value="102" >India</option>
                                                                                            <option value="103" >Indonesia</option>
                                                                                            <option value="106" >Ireland</option>
                                                                                            <option value="108" >Israel</option>
                                                                                            <option value="109" >Italy</option>
                                                                                            <option value="111" >Jamaica</option>
                                                                                            <option value="112" >Japan</option>
                                                                                            <option value="114" >Jordan</option>
                                                                                            <option value="116" >Kenya</option>
                                                                                            <option value="118" >Kuwait</option>
                                                                                            <option value="121" >Latvia</option>
                                                                                            <option value="122" >Lebanon</option>
                                                                                            <option value="127" >Lithuania</option>
                                                                                            <option value="128" >Luxembourg</option>
                                                                                            <option value="129" >Macau</option>
                                                                                            <option value="130" >Macedonia</option>
                                                                                            <option value="131" >Madagascar</option>
                                                                                            <option value="133" >Malaysia</option>
                                                                                            <option value="135" >Mali</option>
                                                                                            <option value="136" >Malta</option>
                                                                                            <option value="140" >Mauritius</option>
                                                                                            <option value="142" >Mexico</option>
                                                                                            <option value="148" >Montserrat</option>
                                                                                            <option value="154" >Nepal</option>
                                                                                            <option value="155" >Netherlands</option>
                                                                                            <option value="157" >New Zealand</option>
                                                                                            <option value="158" >Nicaragua</option>
                                                                                            <option value="159" >Niger</option>
                                                                                            <option value="160" >Nigeria</option>
                                                                                            <option value="165" >Norway</option>
                                                                                            <option value="166" >Oman</option>
                                                                                            <option value="167" >Pakistan</option>
                                                                                            <option value="170" >Panama</option>
                                                                                            <option value="172" >Paraguay</option>
                                                                                            <option value="173" >Peru</option>
                                                                                            <option value="174" >Philippines</option>
                                                                                            <option value="176" >Poland</option>
                                                                                            <option value="177" >Portugal</option>
                                                                                            <option value="179" >Qatar</option>
                                                                                            <option value="181" >Romania</option>
                                                                                            <option value="182" >Russian Federation</option>
                                                                                            <option value="188" >Saudi Arabia</option>
                                                                                            <option value="189" >Senegal</option>
                                                                                            <option value="194" >Singapore</option>
                                                                                            <option value="195" >Slovakia</option>
                                                                                            <option value="196" >Slovenia</option>
                                                                                            <option value="199" >South Africa</option>
                                                                                            <option value="201" >South Korea</option>
                                                                                            <option value="203" >Spain</option>
                                                                                            <option value="204" >Sri Lanka</option>
                                                                                            <option value="212" >Suriname</option>
                                                                                            <option value="215" >Sweden</option>
                                                                                            <option value="216" >Switzerland</option>
                                                                                            <option value="218" >Taiwan</option>
                                                                                            <option value="220" >Tanzania</option>
                                                                                            <option value="221" >Thailand</option>
                                                                                            <option value="226" >Tunisia</option>
                                                                                            <option value="227" >Turkey</option>
                                                                                            <option value="231" >Uganda</option>
                                                                                            <option value="232" >Ukraine</option>
                                                                                            <option value="233" >United Arab Emirates</option>
                                                                                            <option value="234" >United Kingdom</option>
                                                                                            <option value="236" >Uruguay</option>
                                                                                            <option value="239" >Uzbekistan</option>
                                                                                            <option value="242" >Venezuela</option>
                                                                                            <option value="243" >Vietnam</option>
                                                                                            <option value="246" >Yemen</option>
                                                                                    </select>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-group">
                                        <label>App</label>
                                        <select id="app" name="app" class="selectpicker" autocomplete="off" data-size="7" data-width="100%" x-model="app" x-bind:disabled="appLocked" title="Select app">
                                            <template x-for="item in apps">
                                                <option x-bind:value="item.id" x-bind:data-content="getAppDataContent(item)" x-bind:data-app-store="item.app_store.internal_name"></option>
                                            </template>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div x-bind:class="{ 'col-12': !advancedOrder, 'col-6': advancedOrder }">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="advancedOrder" x-model="advancedOrder">
                                        <label class="custom-control-label" for="advancedOrder">Advanced order</label>
                                    </div>
                                </div>
                                <div class="col-6 col-sm-6 d-none" x-bind:class="{ 'd-flex': advancedOrder }">
                                    <div class="form-group mb-0">
                                        <button class="btn btn-outline-primary col-12" type="button" x-on:click="showAddKeywordModal" x-bind:disabled="ordersLocked">Add keywords</button>
                                    </div>
                                </div>
                            </div>

                            <hr />

                            <div class="row">
                                <div class="col-12 ">
                                    <div class="row">
                                        <div x-bind:class="{ 'col-6 col-sm-6': !advancedOrder, 'col-4 col-sm-4': advancedOrder }">
                                            <div class="form-group">
                                                <label>Keyword <small>(only used for installs)</small></label>
                                                <div x-bind:class="{ 'd-none': multiKeywordSelect }">
                                                    <select id="keyword" name="keyword" class="selectpicker" autocomplete="off" x-model="keyword" disabled data-width="100%">
                                                        <option value="0" selected="selected">Select keyword</option>
                                                        <template x-for="item in keywords">
                                                            <option x-bind:value="item.id" x-text="item.name"></option>
                                                        </template>
                                                    </select>
                                                </div>
                                                <div class="d-none" x-bind:class="{ 'd-block': multiKeywordSelect}">
                                                    <select id="keywordMultiple" name="keyword_multiple" class="selectpicker" autocomplete="off" x-model="keyword" disabled data-width="100%" multiple>
                                                        <template x-for="item in keywords">
                                                            <option x-bind:value="item.id" x-text="item.name"></option>
                                                        </template>
                                                    </select>
                                                </div>
                                                <p id="keyword_rank_container" class="d-none" x-bind:class="{ 'd-block': !multiKeywordSelect }">
                                                    Keyword Rank:
                                                    <span class="font-weight-bold" id="keyword_rank" x-text="keywordRank ? keywordRank : ''" x-bind:class="{ 'text-danger': !Number.isInteger(keywordRank), 'text-success': Number.isInteger(keywordRank) }"></span>
                                                    <i class="fa fa-redo fa-spin hidden" x-bind:class="{ 'hidden': !loadingKeyword }"></i>
                                                </p>
                                            </div>
                                        </div>
                                        <div x-bind:class="{ 'col-6 col-sm-6': !advancedOrder, 'hidden': advancedOrder }">
                                            <div class="form-group">
                                                <label>&nbsp;</label>
                                                <button class="btn btn-outline-primary col-12" type="button" x-on:click="showAddKeywordModal" x-bind:disabled="ordersLocked">Add keywords</button>
                                            </div>
                                        </div>
                                        <div class="col-4 col-sm-4" x-bind:class="{ 'd-none': !advancedOrder }">
                                            <div class="form-group">
                                                <label>Search language</label>
                                                <select id="language" name="language" class="selectpicker" autocomplete="off" x-model="language" data-width="100%">
                                                    <option value="">Language (default English)</option>
                                                                                                            <option value="1">Afrikaans</option>
                                                                                                            <option value="2">Amharic</option>
                                                                                                            <option value="3">Bulgarian</option>
                                                                                                            <option value="4">Catalan</option>
                                                                                                            <option value="5">Chinese (Hong Kong)</option>
                                                                                                            <option value="6">Chinese (PRC)</option>
                                                                                                            <option value="7">Chinese (Taiwan)</option>
                                                                                                            <option value="8">Croatian</option>
                                                                                                            <option value="9">Czech</option>
                                                                                                            <option value="10">Danish</option>
                                                                                                            <option value="11">Dutch</option>
                                                                                                            <option value="12">English</option>
                                                                                                            <option value="13">Estonian</option>
                                                                                                            <option value="14">Filipino</option>
                                                                                                            <option value="15">Finnish</option>
                                                                                                            <option value="16">French</option>
                                                                                                            <option value="17">German</option>
                                                                                                            <option value="18">Greek</option>
                                                                                                            <option value="19">Hebrew</option>
                                                                                                            <option value="20">Hindi</option>
                                                                                                            <option value="21">Hungarian</option>
                                                                                                            <option value="22">Icelandic</option>
                                                                                                            <option value="23">Indonesian</option>
                                                                                                            <option value="24">Italian</option>
                                                                                                            <option value="25">Japanese</option>
                                                                                                            <option value="26">Korean</option>
                                                                                                            <option value="27">Latvian</option>
                                                                                                            <option value="28">Lithuanian</option>
                                                                                                            <option value="29">Malay</option>
                                                                                                            <option value="30">Norwegian</option>
                                                                                                            <option value="31">Polish</option>
                                                                                                            <option value="32">Portuguese (Brazil)</option>
                                                                                                            <option value="33">Portuguese (Portugal)</option>
                                                                                                            <option value="34">Romanian</option>
                                                                                                            <option value="35">Russian</option>
                                                                                                            <option value="36">Serbian</option>
                                                                                                            <option value="37">Slovak</option>
                                                                                                            <option value="38">Slovenian</option>
                                                                                                            <option value="39">Spanish</option>
                                                                                                            <option value="40">Swahili</option>
                                                                                                            <option value="41">Swedish</option>
                                                                                                            <option value="42">Thai</option>
                                                                                                            <option value="43">Turkish</option>
                                                                                                            <option value="44">Ukrainian</option>
                                                                                                            <option value="45">Vietnamese</option>
                                                                                                            <option value="46">Zulu</option>
                                                                                                    </select>
                                            </div>
                                        </div>
                                        <div class="col-4 col-sm-4 d-none mt-3" x-bind:class="{ 'd-flex': advancedOrder }">
                                            <label>&nbsp;</label>
                                            <div class="custom-control custom-checkbox mt-3">
                                                <input type="checkbox" class="custom-control-input" id="multiKeywordSelect" x-model="multiKeywordSelect">
                                                <label class="custom-control-label" for="multiKeywordSelect">Multiple keywords</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12" >
                                    <div class="row">
                                        <div x-bind:class="{ 'col-12': !advancedOrder || getAppStoreFromAppId(app) !== 2, 'col-sm-6': advancedOrder && getAppStoreFromAppId(app) === 2}">
                                            <div class="form-group">
                                                <label>Installs</label>
                                                <input type="number" name="installs" class="form-control" id="installs" autocomplete="off" x-model="installs" x-bind:disabled="ordersLocked"/>
                                                <p class="text-muted">Min. 10 per day</p>
                                            </div>
                                        </div>
                                        <div class="col-6 d-none mt-3" x-bind:class="{ 'd-flex': advancedOrder && getAppStoreFromAppId(app) && getAppStoreFromAppId(app) === 2 }">
                                            <label>&nbsp;</label>
                                            <div class="custom-control custom-checkbox mt-3">
                                                <input type="checkbox" class="custom-control-input" id="ipadOrder" x-model="ipadOrder">
                                                <label class="custom-control-label" for="ipadOrder">iPad installs</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row" style="display: none;">
                                <div class="col-12 col-sm-6">
                                    <div class="row">
                                        <div class="col-6 col-sm-6">
                                            <div class="form-group">
                                                <label>Ratings</label>
                                                <input type="number" name="ratings" class="form-control" id="ratings" autocomplete="off" x-model="ratings" x-bind:disabled="ordersLocked"/>
                                                <p class="text-muted">Min. 10 per day</p>
                                            </div>
                                        </div>
                                        <div class="col-6 col-sm-6">
                                            <div class="form-group">
                                                <label>Rating stars</label>
                                                <select name="rate_stars" class="selectpicker" id="ratingStars" autocomplete="off" x-model="ratingStars" x-bind:disabled="ordersLocked" data-width="100%">
                                                    <option value="5" selected="selected">5 Star</option>
                                                    <option value="4">4 Star</option>
                                                    <option value="3">3 Star</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 col-sm-6">
                                    <div class="row">
                                        <div class="col-6 col-sm-4 col-md-4">
                                            <div class="form-group">
                                                <label>Reviews</label>
                                                <input type="number" name="reviews" class="form-control" id="reviews" autocomplete="off" x-model="reviews" x-bind:disabled="ordersLocked || savedCustomReviews !== null"/>
                                                <p class="text-muted mb-0">Min. 5 per day, but 10 per order</p>
                                            </div>
                                        </div>
                                        <div class="col-6 col-sm-4 col-md-4">
                                            <div class="form-group">
                                                <label>Review stars</label>
                                                <select name="rate_stars" class="selectpicker" id="reviewStars" autocomplete="off" x-model="reviewStars" x-bind:disabled="ordersLocked" data-width="100%">
                                                    <option value="5" selected="selected">5 Star</option>
                                                    <option value="4">4 Star</option>
                                                    <option value="3">3 Star</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-12 col-sm-4 col-md-4">
                                            <div class="form-group">
                                                <label class="d-none d-sm-block">&nbsp;</label>
                                                <button class="btn btn-outline-primary col-12" type="button" x-on:click="showCustomReviewsModal" x-bind:disabled="ordersLocked" x-text="savedCustomReviews ? 'Edit reviews' : 'Add reviews'"></button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-12 col-sm-6">
                                    <div class="form-group">
                                        <label>Split order over days (optional)</label>
                                        <input type="number" class="form-control" id="split" name="split" autocomplete="off" x-model="split" x-bind:disabled="ordersLocked">
                                    </div>
                                </div>
                                <div class="col-12 col-sm-6">
                                    <div class="form-group">
                                        <label>Calculated daily (min.10 for installs)</label>
                                        <input type="text" class="form-control" id="calculated" name="calculated" readonly="readonly" autocomplete="off" x-model="computedMaxDaily()">
                                    </div>
                                </div>
                            </div>

                            <p>
                                Consume: <b><span x-text="price"></span></b><br />
                            </p>

                            <h3>Orders</h3>

                            <div class="table-responsive mb-3 mb-md-0">
                                <table class="table">
                                    <thead>
                                    <tr>
                                        <th scope="col">Type</th>
                                        <th scope="col">Keyword <span class="d-none" x-bind:class="{ 'd-inline': multiKeywordSelect}">(Rank)</span></th>
                                        <th scope="col">Installs</th>
                                        <!--<th scope="col">Ratings (Rate stars)</th>
                                        <th scope="col">Reviews</th>-->
                                        <th scope="col">Split</th>
                                        <th scope="col">Consume</th>
                                        <th scope="col"></th>
                                    </tr>
                                    </thead>
                                    <tbody id="orders">
                                    <template x-for="order in orders">
                                        <tr x-bind:class="{ 'table-danger': order.error }">
                                            <td>
                                                <template x-if="order.ipad_order">
                                                    <i class="far fa-tablet-alt"></i>
                                                </template>
                                                <template x-if="!order.ipad_order">
                                                    <i class="far fa-mobile"></i>
                                                </template>
                                            </td>
                                            <td>
                                                <span x-text="order.keyword_name"></span>
                                                <span class="d-none" x-bind:class="{ 'd-inline': multiKeywordSelect}">
                                                    <span class="font-weight-bold" id="keyword_rank" x-text="order.keywordRank ? ('(' + order.keywordRank + ')') : ''" x-bind:class="{ 'text-danger': !Number.isInteger(order.keywordRank), 'text-success': Number.isInteger(order.keywordRank) }"></span>
                                                    <i class="fa fa-redo fa-spin hidden" x-bind:class="{ 'hidden': order.keywordRank !== null }"></i>
                                                </span>
                                            </td>
                                            <td>
                                                <span x-text="order.installs"></span>
                                            </td>
                                           <!-- <td x-text="order.ratings ? order.ratings + ' (' + order.rating_stars + ' stars)' : ''"></td>
                                            <td x-text="order.reviews ? order.reviews + ' (' + order.review_stars + ' stars)' : ''"></td>-->
                                            <td x-text="order.split"></td>
                                            <td x-text="'' + order.price"></td>
                                            <td>
                                                <button class="btn btn-danger remove-order ml-3" title="Delete" type="button" x-on:click="removeOrder(order)" >
                                                    <i class="fa fa-times"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </template>
                                    </tbody>
                                    <tfoot class="d-md-down-none">
                                    <tr>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                        <!-- <td></td>
                                        <td></td>-->
                                        <td></td>
                                        <td class="font-weight-bold" x-text="'$' + computedTotalPrice()"></td>
                                        <td class="font-weight-bold">Total</td>
                                    </tr>
                                    </tfoot>
                                </table>
                            </div>
                            <div class="d-md-block d-lg-none mb-2">
                                Total: <span class="font-weight-bold" x-text="'' + computedTotalPrice()"></span>
                            </div>

                            <div class="row">
                                <div class="col-12 text-right">
                                    <button class="btn btn-primary text-white" type="button" x-bind:disabled="loading || loadingKeyword" x-on:click="addOrder">
                                        Add order
                                    </button>
                                    <button class="btn btn-success" type="button" x-bind:disabled="loading || orders.length === 0" x-on:click="startOrders">
                                        <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" x-bind:class="{ 'hidden': !loading }"></span>
                                        <span class="hidden" x-bind:class="{ 'hidden': !loading }">Loading...</span>
                                        <span x-bind:class="{ 'hidden': loading }">Start orders</span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="addKeywordModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <form id="addKeywordForm">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Add Keyword</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <div class="alert alert-success hidden">
                                The Keywords is now added
                            </div>
                            <fieldset class="form-group">
                                <label>Keyword name</label>
                                <input type="text" class="form-control" autocomplete="off" name="keyword" autofocus>
                                <small>Use comma or press enter to add multiple keywords at once</small>
                            </fieldset>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button class="btn btn-primary" type="button" x-bind:disabled="loadingAddKeywords" x-on:click="addKeywords">
                                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" x-bind:class="{ 'hidden': !loadingAddKeywords }"></span>
                                <span class="hidden" x-bind:class="{ 'hidden': !loadingAddKeywords }">Loading...</span>
                                <span x-bind:class="{ 'hidden': loadingAddKeywords }">Add Keywords</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="modal fade" id="customReviewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Add custom reviews</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-danger" x-bind:class="{ 'hidden': !showCustomReviewsError}">
                            All reviews has to be filled, for both title (iOS only) and content.
                        </div>
                        <div class="alert alert-danger hidden" id="importReviewsError">
                            Could not process the uploaded file. <br />
                            Be sure it's an <b>.csv</b> file, the delimiters used is <b>; (semicolon)</b>, and to add at least 10 reviews.
                        </div>
                        <div class="row mb-2">
                            <div class="col-12">
                                <button class="btn btn-primary" x-on:click="addTenCustomReviews()">Add 10 reviews</button>
                                <button class="btn btn-secondary" x-on:click="showUploadReviews()" x-show="!showUploadReviewsContent">Upload reviews</button>
                                <button class="btn btn-secondary" x-on:click="cancelUploadReviews()" x-show="showUploadReviewsContent">Cancel import</button>
                            </div>
                        </div>
                        <template x-if="!showUploadReviewsContent">
                            <div class="row mb-1">
                                <div class="col-6 font-weight-bold" x-bind:class="{ 'hidden': !isAppAppStore() }">
                                    Title
                                </div>
                                <div class="font-weight-bold" x-bind:class="{ 'col-6': isAppAppStore(), 'col-12': isAppGooglePlay() }">
                                    Content
                                </div>
                            </div>
                        </template>
                        <template x-if="showUploadReviewsContent">
                            <div>
                                <div class="alert alert-info">
                                    Importing reviews, will remove all the ones you might already have added.<br />
                                    The file has to be <b>.csv</b> format, delimiters used has to be <b>; (semicolon)</b>, and at least 10 reviews has to be added.
                                </div>
                                <form action="https://iosinstalls.com/dashboard/new-order/reviews" class="dropzone" id="uploadReviews">
                                    <input type="hidden" name="_token" value="2Uoi3ghRGZ24qqcn4avvFef7BdIpey9e1UvxeT7V">
                                    <div class="dz-message" data-dz-message><span>Only .CSV files accepted.</span></div>
                                    <div class="fallback">
                                        <input name="file" type="file" />
                                    </div>
                                </form>
                            </div>
                        </template>
                        <template x-for="review in customReviews.slice((customReviewsPage - 1) * 10, ((customReviewsPage) * 10))" x-if="!showUploadReviewsContent">
                            <div class="row mt-1">
                                <div class="col-1 text-center align-self-center">
                                    <span x-text="customReviews.indexOf(review) + 1"></span>
                                </div>
                                <div class="col-4" x-bind:class="{ 'hidden': !isAppAppStore() }">
                                    <input type="text" class="form-control" x-model="review.title" />
                                </div>
                                <div x-bind:class="{ 'col-5': isAppAppStore(), 'col-10': isAppGooglePlay() }">
                                    <input type="text" class="form-control" x-model="review.content" />
                                </div>
                                <div class="col-1">
                                    <button class="btn btn-outline-danger" x-on:click="customReviews.splice(customReviews.indexOf(review), 1)" tabindex="-1"><i class="far fa-trash"></i></button>
                                </div>
                            </div>
                        </template>
                        <div class="row mt-2">
                            <div class="col-6 font-weight-bold align-self-center">
                                Total reviews: <span x-text="customReviews.length"></span>
                            </div>
                            <div class="col-6 text-right">
                                <button class="btn btn-outline-primary" x-on:click="prevCustomReviewsPage()"><i class="far fa-chevron-left"></i></button>
                                <button class="btn btn-outline-primary" x-on:click="nextCustomReviewsPage()"><i class="far fa-chevron-right"></i></button>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-primary" type="button" x-on:click="saveCustomReviews">
                            Save reviews
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

            </main>
        </div>

        <footer class="app-footer">
                            &copy; 2021 <?php echo $rowtdk["sitename"];?>. All Rights Reserved
                        <div class="pull-right">
                Server time: <?php echo date('d-m-Y H:i:s',time());?>
            </div>
        </footer>

        <!-- Bootstrap and necessary plugins -->
        <script src="/js/backend.js?id=27298b157affa1f728a9"></script>

            <script type="text/javascript">
        function main() {
            return {
                loading: false,
                loadingKeyword: false,
                appLocked: true,
                ordersLocked: true,
                keywordLocked: true,
                advancedOrder: false,
                multiKeywordSelect: false,
                apps: [],
                keywords: [],
                orders: [],
                prices: {"id":1,"name":"Default","direct_installs":"0.200","targeted_direct_installs":"0.200","keyword_installs":"0.200","targeted_keyword_installs":"0.200","ios_targeted_direct_installs":"0.300","ios_targeted_keyword_installs":"0.200","ratings":"0.100","ios_ratings":"0.100","ios_reviews":"0.200","reviews":"0.200","custom":false,"minimum_spent":"0","active":true,"updated_at":"2020-01-23T11:01:59.000000Z","created_at":"2020-01-23T11:01:59.000000Z"},
                countryPrices: [],
                country: null,
                app: null,
                appStore: null,
                installs: null,
                keyword: null,
                language: null,
                ratings: null,
                ratingStars: 5,
                reviews: null,
                reviewStars: 5,
                savedCustomReviews: null,
                split: null,
                ipadOrder: false,
                price: 0,
                keywordRank: null,
                errorText: [],
                successText: null,
                lowBalance: false,
                loadingAddKeywords: false,
                customReviews: [],
                showCustomReviewsError: false,
                customReviewsPage: 1,
                showUploadReviewsContent: false,
                uploadDropzone: null,
                init() {
                    this.$watch('country', value => this.watchCountry(value))
                    this.$watch('app', value => this.watchApp(value))
                    this.$watch('keyword', value => this.watchKeyword(value))
                    this.$watch('installs', value => this.watchInstalls(value))
                    this.$watch('ratings', value => this.watchRatings(value))
                    this.$watch('reviews', value => this.watchReviews(value))
                    this.$watch('keywordLocked', value => this.watchKeywordLocked(value))
                    this.$watch('advancedOrder', value => this.watchAdvancedOrder(value))
                    this.$watch('multiKeywordSelect', value => this.watchMultiKeywordSelect(value))
                    this.$watch('language', value => this.watchLanguageSelect(value))

                    $('#addKeywordModal input').tagsinput()

                    axios.get('/dashboard/apps.php')
                        .then((response) => {
                            this.apps = response.data

                            this.setAppLocked(false)

                                                    })
                },
                addOrder() {
                    let nextTick = false;
                    if (this.installs == 0) {
                        this.installs = null
                        nextTick = true
                    }

                    //if (this.ratings == 0) {
                       // this.ratings = null
                       // nextTick = true
                    //}

                    //if (this.reviews == 0) {
                       // this.reviews = null
                       // nextTick = true
                    //}

                    if (this.split == 0) {
                        this.split = null
                        nextTick = true
                    }
                    //if (this.installs/this.ratings <10||this.installs/this.reviews <10) {
                        
                        //alert("Every 10 Installs per 1 Ratings or 1 Reviews");
                        //throw SyntaxError();
                    //}

                    if (nextTick) {
                        this.$nextTick(() => {
                            this.addOrderExecute()
                        })
                    } else {
                        this.addOrderExecute()
                    }
                },
                addOrderExecute() {
                    if ($('#new-order').valid()) {
                        this.setAppLocked(true)
                        this.lowBalance = false

                        if (this.multiKeywordSelect && this.keyword) {
                            if (this.computedTotalPrice() + this.price > $('#balance').text()) {
                                this.lowBalance = true
                                return
                            }

                            let price = this.price

                            if (this.keyword.length > 0) {
                                price /= this.keyword.length
                            }

                            this.keyword.forEach(keywordId => {
                                const keyword = this.keywords.filter((item) => {
                                    return item.id === Number.parseInt(keywordId)
                                })[0]

                                this.orders.push({
                                    id: this.orders.length + 1,
                                    app_id: this.app,
                                    country_id: this.country,
                                    keyword_name: keyword ? keyword.name : null,
                                    keyword: Number.parseInt(keywordId),
                                    keyword_rank: null,
                                    language: this.language,
                                    installs: this.installs ? Number.parseInt(this.installs) : undefined,
                                    ratings: this.ratings ? Number.parseInt(this.ratings) : undefined,
                                    rating_stars: this.ratings ? Number.parseInt(this.ratingStars) : undefined,
                                    reviews: this.reviews ? Number.parseInt(this.reviews) : undefined,
                                    review_stars: this.reviews ? Number.parseInt(this.reviewStars) : undefined,
                                    custom_reviews: this.savedCustomReviews ? this.savedCustomReviews : undefined,
                                    split: this.split ? Number.parseInt(this.split) : undefined,
                                    ipad_order: this.ipadOrder ? 1 : 0,
                                    price: price,
                                    error: false
                                })
                            })

                            this.checkKeywordRank(this.keyword)
                        } else {
                            if (this.computedTotalPrice() + this.price > $('#balance').text()) {
                                this.lowBalance = true;
                                return;
                            }

                            const keyword = this.keywords.filter((item) => {
                                return item.id === Number.parseInt(this.keyword)
                            })[0]

                            this.orders.push({
                                id: this.orders.length + 1,
                                app_id: this.app,
                                country_id: this.country,
                                keyword_name: keyword ? keyword.name : null,
                                keyword: this.keyword ? Number.parseInt(this.keyword) : undefined,
                                language: this.language,
                                installs: this.installs ? Number.parseInt(this.installs) : undefined,
                                ratings: this.ratings ? Number.parseInt(this.ratings) : undefined,
                                rating_stars: this.ratings ? Number.parseInt(this.ratingStars) : undefined,
                                reviews: this.reviews ? Number.parseInt(this.reviews) : undefined,
                                review_stars: this.reviews ? Number.parseInt(this.reviewStars) : undefined,
                                custom_reviews: this.savedCustomReviews ? this.savedCustomReviews : undefined,
                                split: this.split ? Number.parseInt(this.split) : undefined,
                                ipad_order: this.ipadOrder ? 1 : 0,
                                price: this.price,
                                error: false
                            })
                        }

                        this.installs = null
                        this.keyword = null
                        this.langauge = null
                        this.ratings = null
                        this.ratingStars = 5
                        this.reviews = null
                        this.reviewStars = 5
                        this.customReviews = []
                        this.savedCustomReviews = null
                        this.split = null
                        this.ipadOrder = false
                        this.price = 0

                        if (!window.onbeforeunload) {
                            window.onbeforeunload = function(evt) {
                                evt = evt || window.event

                                // For IE and Firefox prior to version 4
                                if (evt) {
                                    evt.returnValue = "You haven't started the orders, are you sure you want to leave?"
                                }

                                // For Safari
                                return "You haven't started the orders, are you sure you want to leave?"
                            }
                        }
                    }
                },
                removeOrder(order) {
                    this.orders.splice(this.orders.indexOf(order), 1)
                    if (this.orders.length === 0) {
                        this.setAppLocked(false)
                    }
                },
                startOrders() {
                    this.loading = true

                    let orders = []

                    this.orders.forEach(order => {
                        if (order.error === false) {
                            orders.push(order)
                        }
                    })

                    $.ajax({
                        url: '/dashboard/new-order.php',
                        type: 'POST',
                        data: {
                            country_id: this.country,
                            app_id: this.app,
                            orders: orders
                        },
                        success: (response) => {
                            this.loading = false
                            window.onbeforeunload = null

                            if (response.status == true) {
                                this.successText = response.success

                                this.orders = []
                                this.setAppLocked(false)

                                $('#balance').text(parseFloat(parseFloat($('#balance').text()) - response.usedBalance).toFixed(2));
                                window.scrollTo(0,0);
                            } else {
                                this.errorText = response.messages
                            }
                        },
                        error: (xhr) => {
                            this.loading = false

                            if (xhr.hasOwnProperty("responseJSON")) {
                                this.errorText = '';
                                $.each(xhr.responseJSON.errors, function(key, error){
                                    this.errorsText += error + "<br />";
                                });
                            }
                        }
                    })
                },
                calculatePrice() {
                    let calculatedInstallsPrice = 0
                    let calculatedRatingsPrice = 0
                    let calculatedReviewsPrice = 0

                    const app = this.getAppFromId(this.app)

                    let targetedDirectInstalls,
                        targetedKeywordInstalls,
                        ratings,
                        reviews;

                    let specificPrices = this.countryPrices.filter(data => {
                        if (data.app_store_id == app.app_store.id && this.country == data.country_id) {
                            return true
                        }
                        return false
                    })

                    if (app.app_store.isGooglePlay) {
                        targetedDirectInstalls = this.prices.targeted_direct_installs
                        targetedKeywordInstalls = this.prices.targeted_keyword_installs
                        ratings = this.prices.ratings
                        reviews = this.prices.reviews
                    } else if (app.app_store.isAppStore) {
                        targetedDirectInstalls = this.prices.ios_targeted_direct_installs
                        targetedKeywordInstalls = this.prices.ios_targeted_keyword_installs
                        ratings = this.prices.ios_ratings
                        reviews = this.prices.ios_reviews
                    }

                    if (specificPrices.length == 1) {
                        targetedDirectInstalls = specificPrices[0].direct_installs ? specificPrices[0].direct_installs : targetedDirectInstalls
                        targetedKeywordInstalls = specificPrices[0].keyword_installs ? specificPrices[0].keyword_installs : targetedKeywordInstalls
                        ratings = specificPrices[0].ratings ? specificPrices[0].ratings : ratings
                        reviews = specificPrices[0].reviews ? specificPrices[0].reviews : reviews
                    }

                    if ($.isNumeric(this.installs) && this.installs % 1 === 0) {
                        if (!this.keyword || this.keyword == 0) {
                            calculatedInstallsPrice = this.installs * targetedDirectInstalls
                        } else {
                            calculatedInstallsPrice = this.installs * targetedKeywordInstalls
                        }
                        calculatedInstallsPrice = Math.round(calculatedInstallsPrice * 100) / 100
                    }

                    if ($.isNumeric(this.ratings) && this.ratings % 1 === 0) {
                        calculatedRatingsPrice = this.ratings * ratings
                        calculatedRatingsPrice = Math.round(calculatedRatingsPrice * 100) / 100
                    }

                    if ($.isNumeric(this.reviews) && this.reviews % 1 === 0) {
                        calculatedReviewsPrice = this.reviews * reviews
                        calculatedReviewsPrice = Math.round(calculatedReviewsPrice * 100) / 100
                    }

                    let price = Math.round((calculatedInstallsPrice + calculatedRatingsPrice + calculatedReviewsPrice) * 100) / 100

                    if (this.multiKeywordSelect && this.keyword && this.keyword.length > 0) {
                        price *= this.keyword.length
                    }

                    this.price = Math.round(price * 100) / 100
                },
                fetchKeywords() {
                    this.keywordLocked = true;
                    axios.post('/dashboard/get-keywords2.php', {
                        app_id: this.app
                    }).then(response => {
                        if (response.data.success) {
                            if (response.data.keywords.length !== 0) {
                                const keywords = []
                                Object.keys(response.data.keywords).forEach((item) => {
                                    keywords.push({
                                        id: response.data.keywords[item],
                                        name: item
                                    })
                                })
                                this.keywords = keywords

                                this.$nextTick(() => {
                                    if (this.country) {
                                        this.keywordLocked = false
                                    }
                                })
                            }
                        }
                    })
                },
                showAddKeywordModal() {
                    $('#addKeywordModal').modal('show')
                },
                addKeywords() {
                    this.loadingAddKeywords = true;
                    let alert = $('#addKeywordModal .alert');
                    alert.addClass('hidden');

                    $.ajax({
                        url: "/dashboard/add-keyword.php",
                        type: "POST",
                        data: {
                            "app_id": this.app,
                            "keyword": $('#addKeywordModal input[name=keyword]').val()
                        },
                        success: (response) => {
                            this.loadingAddKeywords = false;

                            if (response.status) {
                                this.loadingAddKeywords = false;
                                this.fetchKeywords();
                                $('#addKeywordModal').modal('hide')
                                $('#addKeywordModal input[name=keyword]').tagsinput('removeAll')
                            } else {
                                this.loadingAddKeywords = false;
                                alert.removeClass('hidden');
                                alert.text(response.errors[0]);
                            }
                        },
                        error: function() {
                            this.loadingAddKeywords = false;
                        }
                    });
                },
                showCustomReviewsModal() {
                    if (this.customReviews.length === 0) {
                        this.addTenCustomReviews()
                    }
                    $('#customReviewsModal').modal('show')
                },
                showUploadReviews() {
                    this.showUploadReviewsContent = true
                    this.$nextTick(() => {
                        this.uploadDropzone = new Dropzone('#uploadReviews')
                    })
                },
                cancelUploadReviews() {
                    this.showUploadReviewsContent = false
                },
                prevCustomReviewsPage() {
                    if (this.customReviewsPage > 1) {
                        this.customReviewsPage--
                    }
                },
                nextCustomReviewsPage() {
                    if (this.customReviewsPage < (this.customReviews.length / 10)) {
                        this.customReviewsPage++
                    }
                },
                saveCustomReviews() {
                    this.showCustomReviewsError = false
                    let error = false

                    if (this.customReviews.length < 10) {
                        error = true
                    }

                    if (!error) {
                        this.customReviews.forEach(review => {
                            if (this.isAppAppStore() && (!review.title || review.title.length < 1)) {
                                error = true
                            }

                            if (!review.content || review.content.length < 1) {
                                error = true
                            }
                        })
                    }

                    if (!error) {
                        this.savedCustomReviews = this.customReviews
                        this.reviews = this.customReviews.length
                        $('#customReviewsModal').modal('hide')
                    } else {
                        this.showCustomReviewsError = true
                    }
                },
                resetCustomReviews() {
                    this.customReviews = [];
                    this.addTenCustomReviews()
                },
                addTenCustomReviews() {
                    for (let i = 0; i < 10; i++) {
                        this.customReviews.push({});
                    }
                },
                setAppLocked(newVal) {
                    this.appLocked = newVal
                    this.$nextTick(() => {
                        $('.selectpicker').selectpicker('refresh')
                    })
                },
                setOrderLocked(newVal) {
                    this.ordersLocked = newVal
                    this.$nextTick(() => {
                        $('.selectpicker').selectpicker('refresh')
                    })
                },
                getAppFromId(id) {
                    return this.apps.filter((app) => {
                        return app.id == id
                    })[0]
                },
                getAppDataContent(app) {
                    return '<img src="/images/stores/' + app.app_store.icon + '" height="20px" style="margin-right: 20px" /><img src="' + app.icon + '" height="40px" style="margin-right: 10px" />' + app.name
                },
                getAppStoreFromAppId(id) {
                    if (!id) {
                        return false
                    }

                    return this.getAppFromId(id).app_store.id
                },
                isAppGooglePlay() {
                    return this.app && this.getAppFromId(this.app).app_store.isGooglePlay;
                },
                isAppAppStore() {
                    return this.app && this.getAppFromId(this.app).app_store.isAppStore;
                },
                checkKeywordRank(keyword) {
                    this.keywordRank = null

                    if (keyword && keyword !== "0") {
                        this.loadingKeyword = true

                        axios.post("https://iosinstalls.com/dashboard/update-keyword-rank", {
                            country_id: this.country,
                            keyword_id: keyword,
                            language_id: this.language
                        }).then(response => {
                            this.loadingKeyword = false

                            if (Array.isArray(response.data.rank)) {
                                response.data.rank.forEach(rank => {
                                    this.orders.forEach(order => {
                                        if (order.keyword === rank.keyword_id) {
                                            order.keywordRank = rank.rank;
                                            if (rank.error === true) {
                                                order.error = true;
                                            }
                                        }
                                    })
                                })
                            } else {
                                if (!this.multiKeywordSelect && this.keyword) {
                                    if (response.data.success) {
                                        this.keywordRank = response.data.rank
                                    } else {
                                        this.keywordRank = response.data.error
                                    }
                                }
                            }
                        }).catch(errors => {
                            if (!this.multiKeywordSelect && this.keyword) {
                                this.loadingKeyword = false
                                this.keywordRank = errors.response.data.errors.keyword_id[0]
                            }
                        })
                    } else {
                        this.keyword = null
                    }
                },
                computedTotalPrice() {
                    const total = this.orders.reduce((a, b) => a + b.price, 0)
                    return Math.round(total * 100) / 100
                },
                computedMaxDaily() {
                    if (!this.split) {
                        return null
                    }

                    if (this.installs) {
                        return Math.floor(this.installs / this.split)
                    //} else if (this.ratings) {
                    //    return Math.floor(this.ratings / this.split)
                    //} else if (this.reviews) {
                    //    return Math.floor(this.reviews / this.split)
                    }

                    return null
                },
                addImportedReviews(reviews) {
                    let customReviews = []

                    reviews.forEach(review => {
                        if (this.isAppAppStore()) {
                            customReviews.push({
                                title: review[0],
                                content: review[1]
                            })
                        } else if (this.isAppGooglePlay()) {
                            customReviews.push({
                                title: null,
                                content: review[0]
                            })
                        }
                    })

                    this.customReviews = customReviews
                    this.showUploadReviewsContent = false
                },
                watchCountry(country) {
                    if (country) {
                        if (this.app) {
                            this.setOrderLocked(false)

                            if (this.keywords.length > 0) {
                                this.keywordLocked = false

                                if (this.keyword && !this.multiKeywordSelect) {
                                    this.checkKeywordRank(this.keyword)
                                }
                            }

                            this.calculatePrice()
                        }
                    } else {
                        this.keywordLocked = true
                        this.setOrderLocked(true)
                    }
                },
                watchApp(app) {
                    //this.resetCustomReviews()
                    this.keywords = []
                    this.keyword = null
                    if (app) {
                        if (this.country) {
                            this.setOrderLocked(false)
                        }
                        this.fetchKeywords()
                    } else {
                        this.keywordLocked = true
                        this.setOrderLocked(true)
                    }

                    this.calculatePrice()
                },
                watchKeyword(keyword) {
                    if (keyword === null) {
                        this.$nextTick(() => {
                            $('#keyword').selectpicker('refresh')
                            $('#keywordMultiple').selectpicker('refresh')
                        })
                    }

                    if (!this.multiKeywordSelect) {
                        this.checkKeywordRank(keyword)
                    }
                    this.calculatePrice()
                },
                watchInstalls(installs) {
                    this.calculatePrice()
                },
                watchRatings(ratings) {
                    this.calculatePrice()
                },
                watchReviews(reviews) {
                    this.calculatePrice()
                },
                watchKeywordLocked(value) {
                    let keywordPicker = $('#keyword')
                    let keywordMultiPicker = $('#keywordMultiple')
                    if (value) {
                        keywordPicker.attr('disabled', true)
                        keywordMultiPicker.attr('disabled', true)
                    } else {
                        keywordPicker.removeAttr('disabled')
                        keywordMultiPicker.removeAttr('disabled')
                    }
                    keywordPicker.selectpicker('refresh')
                    keywordMultiPicker.selectpicker('refresh')
                },
                watchAdvancedOrder(value) {
                    if (!value && this.multiKeywordSelect) {
                        this.keyword = null
                    }
                    this.ipadOrder = false
                    this.multiKeywordSelect = false
                },
                watchMultiKeywordSelect(value) {
                    this.keyword = null
                    this.keywordRank = null
                    this.loadingKeyword = false
                },
                watchLanguageSelect(value) {
                    this.checkKeywordRank(this.keyword)
                    $('#language').selectpicker('refresh')
                }
            }
        }

        jQuery.validator.addMethod("keywordRank", function(value, element) {
            return $('#keyword_rank').text() < 1500;
        }, "The Keyword Rank has to be within top 1500");

        $(function() {
            $.validator.addMethod(
                "calculatedSplit",
                function(value, element) {
                    let minDaily = 10
                    // if ($('#reviews').val()) {
                    //     minDaily = 5
                    // }

                    return $('#split').val() == 0 || $('#calculated').val() >= minDaily;
                },
                //"The calculated split has to be above 5 for reviews, or 10 for installs/ratings"
                "The calculated split has to be above 10 for installs"
            );

            // $.validator.addMethod(
            //     "customRequired",
            //     function(value, element) {
            //         if ($(element).attr('id') === 'installs') {
            //             if (value || $('#ratings').val() || $('#reviews').val()) {
            //                 return true
            //             }
            //         } else if ($(element).attr('id') === 'ratings') {
            //             if (value || $('#installs').val() || $('#reviews').val()) {
            //                 return true
            //             }
            //         } else if ($(element).attr('id') === 'reviews') {
            //             if (value || $('#installs').val() || $('#ratings').val()) {
            //                 return true
            //             }
            //         }

            //         return false
            //     },
            //     "Either Installs, Ratings or Reviews has to be filled"
            // );
            

            $('#new-order').validate({
                onfocusout: false,
                onkeyup: false,
                rules: {
                    "country": {
                        required: true
                    },
                    "app": {
                        required: true
                    },
                    "keyword": {
                        required: false,
                        number: true,
                        keywordRank: true
                    },
                    "installs": {
                        required: true,
                        number: true,
                        min: 10
                    },
                    // "ratings": {
                    //     required: false,
                    //     number: true,
                    //     min: 1
                    // },
                    // "reviews": {
                    //     required: false,
                    //     number: true,
                    //     min: 1
                    // },
                    "split": {
                        required: false,
                        number: true,
                        min: 0,
                        max: 14
                    },
                    "calculated": {
                        required: false,
                        number: true,
                        calculatedSplit: true
                    }
                },
                messages: {
                    "app": 'Please choose the app you want to promote',
                    "split": 'Minimum split is 0, and maximum split is 14',
                    //"calculated": 'Min. daily reviews is 5, and 10 for installs/ratings',
                    "calculated": 'Min. 10 for installs',
                },
                errorElement: 'div',
                errorPlacement: function ( error, element ) {
                    // Add the `help-block` class to the error element
                    error.addClass( 'form-control-feedback' );
                    if ($(element).hasClass('selectpicker')) {
                        error.insertAfter($(element).parent().last());
                    } else {
                        error.insertAfter($(element));
                    }
                },
                highlight: function ( element, errorClass, validClass ) {
                    $( element ).addClass( 'form-control-danger' ).removeClass( 'form-control-success' );
                    $( element ).parents( '.form-group' ).addClass( 'has-danger' ).removeClass( 'has-success' );
                },
                unhighlight: function (element, errorClass, validClass) {
                    $( element ).addClass( 'form-control-success' ).removeClass( 'form-control-danger' );
                    $( element ).parents( '.form-group' ).addClass( 'has-success' ).removeClass( 'has-danger' );
                }
            });

            $('#addKeywordForm').validate( {
                rules: {
                    "keyword": 'required'
                },
                messages: {
                    "keyword": 'Please enter the keywords you would like to add'
                },
                errorElement: 'div',
                errorPlacement: function ( error, element ) {
                    // Add the `help-block` class to the error element
                    error.addClass( 'form-control-feedback' );
                    error.insertAfter( $(element).parent() );
                },
                highlight: function ( element, errorClass, validClass ) {
                    $( element ).addClass( 'form-control-danger' ).removeClass( 'form-control-success' );
                    $( element ).parents( '.form-group' ).addClass( 'has-danger' ).removeClass( 'has-success' );
                },
                unhighlight: function (element, errorClass, validClass) {
                    $( element ).addClass( 'form-control-success' ).removeClass( 'form-control-danger' );
                    $( element ).parents( '.form-group' ).addClass( 'has-success' ).removeClass( 'has-danger' );
                }
            });
        });

        Dropzone.autoDiscover = false;
        Dropzone.options.uploadReviews = {
            paramName: "file", // The name that will be used to transfer the file
            maxFilesize: 10, // MB
            acceptedFiles: '.csv',
            addRemoveLinks: true,
            maxFiles: 1,
            maxfilesexceeded: function(file) {
                this.removeAllFiles();
                this.addFile(file)
            },
            success: function(files, response) {
                this.removeAllFiles()
                let alpine = document.querySelector('[x-data]').__x.$data

                if (response.data && response.data[0].length >= 10) {
                    alpine.addImportedReviews(response.data[0])
                } else {
                    $('#importReviewsError').removeClass('hidden')
                }
            }
        };
    </script>

                        </body>
</html>